﻿/*----------------------------------------------------------------
//  <copyright file="AuthorizationFilter.cs" company="MicroCloud@151504200868">
//      Copyright © 2020-2024 MicroCloud Corporation, All rights reserved.
//  </copyright>
//  <site>https://gitee.com/chenmm123/microclouds</site>
//  <last-editor>cmm</last-editor>
//  <last-date>2022-11-15 14:30</last-date>
//----------------------------------------------------------------*/

namespace MicroCloud.Hangfire.Dashboard.Authorization
{
    #region "表示身份验证的Hangfire授权筛选器"
    /// <summary>
    /// 表示身份验证的Hangfire授权筛选器
    /// </summary>
    public class AuthorizationFilter : IDashboardAuthorizationFilter
    {
        #region "属性"
        #region "获取或设置 用户信息"
        private string[] _users = Array.Empty<string>();
        /// <summary>
        /// 获取或设置 用户信息
        /// </summary>
        public string[] Users
        {
            get { return _users ?? Array.Empty<string>(); }
            set { _users = value; }
        }
        #endregion
        #region "获取或设置 角色信息"
        private string[] _roles = Array.Empty<string>();
        /// <summary>
        /// 获取或设置 角色信息
        /// </summary>
        public string[] Roles
        {
            get { return _roles ?? Array.Empty<string>(); }
            set { _roles = value; }
        }
        #endregion

        #endregion

        #region "方法"
        #region "授权"
        /// <summary>
        /// 授权
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public bool Authorize(DashboardContext context)
        {
            HttpContext httpContext = context.GetHttpContext();
            ClaimsPrincipal principal = httpContext.User;
            if (principal == null || principal.Identity == null || !principal.Identity.IsAuthenticated)
            {
                return false;
            }
            if (principal.Identity is not ClaimsIdentity identity)
            {
                return false;
            }
            if (Users.Length > 0 && !Users.Contains(principal.Identity.Name, StringComparer.OrdinalIgnoreCase))
            {
                return false;
            }
            if (Roles.Length > 0 && !Roles.Any(principal.IsInRole))
            {
                return false;
            }

            return true;
        }
        #endregion

        #endregion

    }
    #endregion

}
